﻿using System.Reflection;
using System.Reflection.Emit;
using rpc_service.cache;
using rpc_service.core.support.assembly.il.http.get;
using rpc_service.core.support.assembly.il.http.post;

namespace rpc_service.core.support.assembly.il;

public class ILGenerateMethod
{
    public void CreateRPCMethod(TypeBuilder typeBuilder, Type type, MethodInfo targetMethod, ILStep[] steps)
    {
        // 创建方法构建器
        MethodBuilder methodBuilder = getMethodBuilder(typeBuilder, targetMethod);
        
        ILGenerator il = methodBuilder.GetILGenerator();
        
        // 声明返回变量
        LocalBuilder result = il.DeclareLocal("string".GetTypeByStr());

        foreach (ILStep step in steps)
        {
            step.Process(il, result, type, targetMethod);
        }
    }

    private MethodBuilder getMethodBuilder(TypeBuilder typeBuilder, MethodInfo targetMethod)
    {
        string methodName = targetMethod.Name;
        Type returnType = targetMethod.ReturnType!;

        Type[] paramTypes = targetMethod.GetParameters().Select(p => p.ParameterType).ToArray();

        return typeBuilder.DefineMethod(
            methodName,
            MethodAttributes.Public | MethodAttributes.Virtual,
            returnType,
            paramTypes
        );
    }
}